package curl

import (
	"gitee.com/teval/goz"
)

// 使用全局client，防止linux主机产生大量ESTABLISHED状态的连接不关闭
// var client = goz.NewClient()

// Get 发送请求
func Get(url string, options ...goz.Options) (goz.ResponseBody, error) {
	return do("GET", url, options...)
}

// GetResp 发送请求
func GetResp(url string, options ...goz.Options) (*goz.Response, error) {
	return doWithResp("GET", url, options...)
}

// Post 发送请求
func Post(url string, options ...goz.Options) (b goz.ResponseBody, e error) {
	return do("POST", url, options...)
}

// PostResp 发送请求
func PostResp(url string, options ...goz.Options) (*goz.Response, error) {
	return doWithResp("POST", url, options...)
}

func Put(url string, options ...goz.Options) (b goz.ResponseBody, e error) {
	return do("PUT", url, options...)
}

func PutResp(url string, options ...goz.Options) (*goz.Response, error) {
	return doWithResp("PUT", url, options...)
}

func Patch(url string, options ...goz.Options) (b goz.ResponseBody, e error) {
	return do("PATCH", url, options...)
}

func PatchResp(url string, options ...goz.Options) (*goz.Response, error) {
	return doWithResp("PATCH", url, options...)
}

func Delete(url string, options ...goz.Options) (b goz.ResponseBody, e error) {
	return do("DELETE", url, options...)
}

func DeleteResp(url string, options ...goz.Options) (*goz.Response, error) {
	return doWithResp("DELETE", url, options...)
}

// do 发送请求
func do(method, url string, options ...goz.Options) (b goz.ResponseBody, e error) {
	if len(options) > 0 {
		options[0].Debug = options[0].Debug || IsDebug()
	}

	cli := goz.NewClient()
	r, e := cli.Request(method, url, options...)

	if e != nil {
		return
	}

	return r.GetBody()
}

// doWithResp 发送请求，返回goz.Response
func doWithResp(method, url string, options ...goz.Options) (r *goz.Response, e error) {
	if len(options) > 0 {
		options[0].Debug = options[0].Debug || IsDebug()
	}

	cli := goz.NewClient()
	return cli.Request(method, url, options...)
}

func ParseProxy(proxies ...string) (proxy string) {
	if len(proxies) > 0 {
		proxy = proxies[0]
	}
	return
}
